package com.poker.duiued;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.poker.iuious.yhyhjs.jklimj.User;
import com.poker.jkiuus.R;
import com.poker.jkiuus.uyrfgd.AppManager;
import com.poker.jkiuus.uyrfgd.DatabaseHelper;
import com.poker.jkiuus.uyrfgd.MD5Utils;

public class RegisterActivity extends AppCompatActivity {
    private EditText et_user_name;
    private EditText et_user_email;
    private EditText et_psw;
    private EditText et_cpsw;
    private Button btn_register;
    private TextView tv_login;
    private CheckBox checkbox_agree;
    private String userName;
    private DatabaseHelper databaseHelper;
    private Toast currentToast;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        AppManager.addActivity(this);
        databaseHelper = new DatabaseHelper(this);

        initView();


    }

    public void initView(){
        et_user_name = findViewById(R.id.et_user_name);
        et_user_email = findViewById(R.id.et_user_email);
        et_psw = findViewById(R.id.et_psw);
        et_cpsw = findViewById(R.id.et_cpsw);
        btn_register = findViewById(R.id.btn_register);
        tv_login = findViewById(R.id.tv_login);
        checkbox_agree = findViewById(R.id.checkbox_agree);

        btn_register.setOnClickListener(v -> {
            if (!checkbox_agree.isChecked()) {

                if (currentToast != null){
                    currentToast.cancel();
                }
                currentToast = Toast.makeText(RegisterActivity.this, "Please read and agree to the Privacy Policy first.", Toast.LENGTH_SHORT);
                currentToast.show();
                return;
            }
            registerUser();
        });

        et_user_email.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (isValidEmail(et_user_email.getText().toString())) {
                    et_user_email.setError("Invalid email address");
                }
            }
        });

        checkbox_agree.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked && buttonView.isPressed()) {

                showPrivacyPolicyDialog();

                checkbox_agree.setChecked(false);
            }
        });

        tv_login.setOnClickListener(v -> {
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.slide_up, R.anim.slide_down);
            finish();
            RegisterActivity.super.finish();
        });
    }

    private void registerUser() {
        String name = et_user_name.getText().toString().trim();
        String email = et_user_email.getText().toString().trim();
        String psw = et_psw.getText().toString().trim();
        String cpsw = et_cpsw.getText().toString().trim();
        boolean userByName = databaseHelper.queryUserByName(name);
        boolean userByEmail = databaseHelper.queryUserByEmail(email);

        if (name.length() <= 0 || email.length() <= 0 || psw.length() <= 0 || cpsw.length() <= 0){
            showRegisterDialog("Please don't leave it blank!",false);
        }else if(userByName){
            showRegisterDialog("The account already exists!Please register again!",false);
            et_user_name.setError("The account already exists!Please register again!");
        }else if (userByEmail){
            showRegisterDialog("The email address already exists!",false);
            et_user_email.setError("The email address already exists!");
        }else if(isValidEmail(email)){
            showRegisterDialog("Invalid email address!",false);
            et_user_email.setError("Invalid email address!");
        }else if (!psw.equals(cpsw)){
            showRegisterDialog("The password is inconsistent twice!",false);
            et_cpsw.setError("The password is inconsistent twice!");
        }else {
            psw = MD5Utils.string2MD5(psw);
            User user = new User(name,psw,email);
            System.out.println(user);
            boolean b = databaseHelper.insertData(user);
            if (b){
                showRegisterDialog("Registration Successful!",true);
            }else {
                showRegisterDialog("Registration failed!Please try again later!",false);
            }
        }
    }

    private void showPrivacyPolicyDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_privacy_policy, null);

        ScrollView scrollView = dialogView.findViewById(R.id.scroll_privacy_policy);
        TextView textView = dialogView.findViewById(R.id.textview_privacy_policy);

        String fullText = getString(R.string.privacy_policy_content);
        String googlePlayServices = getString(R.string.google_play_services);
        String chatRobot = getString(R.string.chat_robot);

        SpannableString ss = new SpannableString(fullText);
        int gpsStart = fullText.indexOf(googlePlayServices);
        int gpsEnd = gpsStart + googlePlayServices.length();
        ss.setSpan(new URLSpan("https://www.google.com/policies/privacy/"), gpsStart, gpsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new ForegroundColorSpan(Color.BLUE), gpsStart, gpsEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new UnderlineSpan(), gpsStart, gpsEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


        int crStart = fullText.indexOf(chatRobot);
        int crEnd = crStart + chatRobot.length();
        ss.setSpan(new URLSpan("https://sites.google.com/view/chat-robot-privacy"), crStart, crEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new ForegroundColorSpan(Color.BLUE), crStart, crEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new UnderlineSpan(), crStart, crEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


        textView.setText(ss);
        textView.setTextSize(16);
        textView.setMovementMethod(LinkMovementMethod.getInstance());

        builder.setView(dialogView)
                .setTitle("ChatRobot Privacy Policy")
                .setPositiveButton("Agree", (dialog, id) -> {

                    checkbox_agree.setChecked(true);
                })
                .setNegativeButton("Cancel", (dialog, id) -> {

                    dialog.cancel();
                });

        AlertDialog dialog = builder.create();


        scrollView.getViewTreeObserver().addOnScrollChangedListener(() -> {
            if (textView.getHeight() - scrollView.getHeight() == scrollView.getScrollY()) {
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
            }
        });

        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    }

    private void showRegisterDialog(String message,boolean flag) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("PROMPT");
        builder.setMessage(message);
        builder.setPositiveButton("OK", (dialog, which) -> {
            if (flag) {
                Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
                intent.putExtra("USER_NAME",userName);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_out_left, R.anim.slide_in_right);
                dialog.dismiss();
                finish();
                super.finish();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private boolean isValidEmail(String email) {
        return !Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }


}
